package com.qq.server.dao;

import com.qq.server.entity.Friend;
import com.qq.server.tools.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author weiBin
 * @date 2019/1/10
 */
public class FriendDaoImpl implements FriendDao {
    @Override
    public void addFriend(Friend friend) {
        Connection conn = DBUtil.getConn();
        String sql = "insert into friend(FROM_USER_ID,TO_USER_ID,STATUS) values(?,?,?)";
        try {
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, friend.getFromUserId());
            statement.setString(2, friend.getToUserId());
            statement.setString(3, friend.getStatus());
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn);
        }
    }

    @Override
    public void updateFriend(Friend friend) {
        Connection conn = DBUtil.getConn();
        String sql = "update friend set status =? where FROM_USER_ID = ? and TO_USER_ID = ?";
        try {
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, friend.getStatus());
            statement.setString(2, friend.getFromUserId());
            statement.setString(3, friend.getToUserId());
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn);
        }
    }

    @Override
    public void removeFriend(Friend friend) {
        Connection conn = DBUtil.getConn();
        String sql = "delete from friend where FROM_USER_ID = ? and TO_USER_ID = ?";
        try {
            //关闭自动提交
            conn.setAutoCommit(false);
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, friend.getFromUserId());
            statement.setString(2, friend.getToUserId());
            int i = statement.executeUpdate();
            if (i > 0) {
                statement.setString(1, friend.getToUserId());
                statement.setString(2, friend.getFromUserId());
                int j = statement.executeUpdate();
                if (j > 0) {
                    //提交
                    conn.commit();
                } else {
                    //回滚
                    conn.rollback();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn);
        }
    }
}
